@using DashboardService.Api.Queries
@using DashboardService.Api.Queries.Dtos
<Card>
    <CardHeader>
        Sales Trends
    </CardHeader>
    <CardBody>
        <LineChart
            Options="options"
            OptionsObject="new { animation = new { duration = 0 }, hover = new { animationDuration = 0 }, responsiveAnimationDuration = 0 }" 
            TItem="decimal"
            @ref="lineChart">

        </LineChart>
    </CardBody>
</Card>

@code {
    [Parameter]
    public DateTime PeriodFrom { get; set; }
    
    [Parameter]
    public DateTime PeriodTo { get; set; }
    
    [Inject]
    private DashboardClient DashboardClient { get; set; }

    private LineChart<decimal> lineChart;
    
    private readonly LineChartOptions options = new LineChartOptions
    {
        Responsive = true,
        MaintainAspectRatio = false
    };
    
    protected override async Task OnAfterRenderAsync( bool firstRender )
    {
        if (firstRender)
        {
            await HandleRedraw();
        }
    }

    private async Task HandleRedraw()
    {
        
        var trendsData = await LoadData();
        
        await lineChart.Clear();
        
        await lineChart.AddLabelsDatasetsAndUpdate
        (
            trendsData.PeriodsSales.Select(ps=>ps.Period).ToList(),
            new LineChartDataset<decimal>()
            {
                Label = "Agents sales (EUR)",
                Data = trendsData.PeriodsSales.Select(ps=>ps.Sales.PremiumAmount).ToList(),
                BorderWidth = 1, 
                BackgroundColor = "rgba(138, 22, 82, 0.8)"
            }
        );
    }

    private async Task<GetSalesTrendsResult> LoadData()
    {
        var getAgentsSales = await DashboardClient.GetSalesTrends(new GetSalesTrendsQuery
        {
            SalesDateFrom = PeriodFrom,
            SalesDateTo = PeriodTo,
            Unit = TimeUnit.Month
        });
        
        return getAgentsSales.Result;
    }
}